package com.yanqu.road.web.controller.game;

import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.enums.eItemId;
import com.yanqu.road.entity.enums.eReduceItemStatus;
import com.yanqu.road.entity.platform.PlatformReduceItemOrder;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.web.HttpJsonWebParam;
import com.yanqu.road.logic.bussiness.platform.ReduceItemBussiness;
import com.yanqu.road.logic.bussiness.player.UserBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.server.helper.SignHelper;
import com.yanqu.road.server.manger.AppKeyMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.web.WebServer;
import com.yanqu.road.web.controller.BaseJsonHttpServlet;
import com.yanqu.road.webservice.invoke.GameWebServiceInvoke;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.SortedMap;

@WebServlet(urlPatterns = "/reduceToken")
public class ReduceToken extends BaseJsonHttpServlet {

	private static Logger logger = LogManager.getLogger(ReduceToken.class.getName());

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		logger.info("request reduceToken");
		HttpJsonWebParam httpJsonWebParam = super.parseRequest(request);
		JSONObject paramObj = httpJsonWebParam.getParamObj();

		JSONObject result = new JSONObject();

		String orderID;
		String orderType;
		String platformUserId;
		long serverID;
		long userId;
		long voucherNum;
		long refundTime;
		String cmd;
		String cpOrderID;
		String productID;
		String cpProductID;
		String remark;
		String sign;
		try{
			orderID = paramObj.getString("orderID");
			orderType = paramObj.getString("orderType");
			platformUserId = paramObj.getString("userID");
			serverID = paramObj.getLongValue("serverID");
			userId = paramObj.getLongValue("roleID");
			voucherNum = paramObj.getLongValue("voucherNum");
			refundTime = paramObj.getLongValue("refundTime");
			cmd = paramObj.getString("cmd");
			cpOrderID = paramObj.getString("cpOrderID");
			productID = paramObj.getString("productID");
			cpProductID = paramObj.getString("cpProductID");
			remark = paramObj.getString("remark");
			sign = paramObj.getString("sign");
		} catch (Exception e){
			logger.error("reduceToken argument error:" + e);
			sendResult(response, 0, "argument error");
			return;
		}
		try{
			SortedMap<String, String> paramMap = SignHelper.getParamMap(paramObj);
			if(!SignHelper.checkSign(paramMap, AppKeyMgr.getAndroidAppSecret(), sign)){
				if(ServerListMgr.isCnMergeServer(WebServer.getInstance().getServerId())){
					if(!SignHelper.checkSign(paramMap, ChannelConfig.APP_SECRET_CONFIG, sign)){
						logger.error("reduceToken sign校验不通过");
						sendResult(response, 0, "reduceToken sign校验不通过");
						return;
					}
				}else {
					logger.error("reduceToken sign校验不通过");
					sendResult(response, 0, "reduceToken sign校验不通过");
					return;
				}
			}
			// 掌柜通宝
			int itemId = eItemId.GOLD_TOKEN.getValue();

			UserInfo userInfo = UserBussiness.getUserInfoByUserId(userId);
			if (null == userInfo) {
				logger.error("reduceToken user no find,orderNo:{},userId{}", orderID, userId);
				sendResult(response, 0, "role no find");
				return;
			}
			// 先获取下订单
			PlatformReduceItemOrder reduceItemOrder = ReduceItemBussiness.getPlatformReduceItemOrder(orderID);
			// 检测订单状态
			int type = 0;
			if (orderType.equals("refund")) {
				if (reduceItemOrder != null && reduceItemOrder.getStatus() == eReduceItemStatus.AlreadyReduce.getValue()) {
					sendResult(response, 2, "订单已退款");
					return;
				}
				type = 1;
			} else if (orderType.equals("supplement")) {
				// 增加
				if (reduceItemOrder == null || reduceItemOrder.getStatus() != eReduceItemStatus.AlreadyReduce.getValue()) {
					sendResult(response, 0, "订单非退款状态");
					return;
				}
				type = 2;
			} else {
				logger.error("reduceToken orderType error,orderNo:{},type:{}", orderID, orderType);
				sendResult(response, 0, "orderType error");
				return;
			}
			if (reduceItemOrder == null) {
				// 空的初始化一个订单
				reduceItemOrder = new PlatformReduceItemOrder();
			}
			reduceItemOrder.setOrderNo(orderID);
			reduceItemOrder.setUserId(userId);
			reduceItemOrder.setItemId(itemId);
			reduceItemOrder.setItemCount(voucherNum);
			// 订单类型
			reduceItemOrder.setOrderType(type);
			reduceItemOrder.setServerId(serverID);
			reduceItemOrder.setPlatformUserId(platformUserId);
			reduceItemOrder.setRefundTime(refundTime);
			reduceItemOrder.setCmd(cmd);
			reduceItemOrder.setCpOrderId(cpOrderID);
			reduceItemOrder.setProductId(productID);
			reduceItemOrder.setCpProductId(cpProductID);
			reduceItemOrder.setRemark(remark);
			reduceItemOrder.setSign(sign);
			if (!ReduceItemBussiness.addPlatformReduceItemOrder(reduceItemOrder)) {
				logger.error("reduceToken fail,add to db fail,orderNo:{},userId:{},count:{}", orderID, userId, voucherNum);
				sendResult(response, 0, "add to db fail");
				return;
			}
			sendMessage(response, GameWebServiceInvoke.reduceToken(orderID));
		} catch (Exception e) {
			logger.error("reduceToken error:" + e);
			sendResult(response, 0, "other error");
		}
	}
}
